/**
 * gislin 2017年7月11日
 */
package com.btcode.db.executer;

import com.btcode.db.config.DataBaseConfig;
import com.btcode.db.connection.IConnectionGetter;
import com.btcode.db.conver.DefaultValueConver;
import com.btcode.db.conver.IValueConver;
import com.btcode.db.result.PageResult;
import com.btcode.db.result.Row;
import com.btcode.db.sqlparameter.PageInfo;
import com.btcode.db.sqlparameter.SQLParameterList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author gislin 2017年7月11日
 */
public class MySQLDataExecuter extends BaseDataExecuter {

    public MySQLDataExecuter(DataBaseConfig config, IConnectionGetter connectionGetter) {
        super(config, connectionGetter);
    }

    @Override
    public PageResult queryListPage(String sql, SQLParameterList parms, PageInfo pageInfo) {
        sql = coverSqlToMysql(sql);

        String countSQL = " SELECT COUNT(*) FROM (" + sql + ") t ";
        Object countObj = queryScalar(countSQL, parms);

        IValueConver conver = new DefaultValueConver();
        int recordCount = conver.converToInteger(countObj);
        int pageCount = (int) Math.ceil(recordCount * 1.0 / pageInfo.getPageSize());
        int pageIndex = pageInfo.getPageIndex() > pageCount ? pageCount : pageInfo.getPageIndex();
        int offset =  Math.max(0, (pageIndex - 1) * pageInfo.getPageSize());
        pageInfo.setPageCount(pageCount);
        pageInfo.setPageIndex(pageIndex);
        pageInfo.setRecordCount(recordCount);

        String pageSqlMysql = sql + " limit  " +pageInfo.getPageSize()+ " offset " + offset;
        List<Row> rows = executeQuery(pageSqlMysql, parms);

        PageResult result = new PageResult(pageInfo, rows);

        return result;
    }

    @Override
    public List<Row> queryList(String sql, SQLParameterList parms) {
        sql = coverSqlToMysql(sql);
        return super.queryList(sql, parms);
    }

    /**
     * 将oracle Sql格式转换成mysql格式
     * 目前只实现to_date语法的转换，其他还需要拓展的后续补充
     * 注意：mysql语法里面的str_to_date不能再使用
     * @return
     */
    private String coverSqlToMysql(String sql){
        String rex="\\bto_date\\(.*?\\B\\)";
        Pattern pattern=Pattern.compile(rex);
        Matcher matcher=pattern.matcher(sql);
        while (matcher.find()){
            String repStr = matcher.group();
            String[] arrStr = repStr.split(",");
            repStr = arrStr[0].split("\\(")[1];
            sql = sql.replace(matcher.group(),repStr);
        }
        if(sql.contains("sysdate") || sql.contains("SYSDATE")){
            sql = sql.replaceAll("sysdate","NOW()");
            sql = sql.replaceAll("SYSDATE","NOW()");
        }
        if(sql.contains("to_char") || sql.contains("TO_CHAR")){
            sql = sql.replaceAll("to_char","date_format");
            sql = sql.replaceAll("TO_CHAR","date_format");
            sql = sql.replaceAll("yyyy-mm-dd","%Y-%m-%d");
            sql = sql.replaceAll("hh24:mi:ss","%H-%i-%S");
        }
        return sql;
    }

}
